<template>
  <div>
    <search-cirteria v-model:name="queryParams.name" />
    <div class="table-container">
      <table-operate>
        <n-button
          size="small"
          type="primary"
          @click="handleShowModal"
        >
          <template #icon>
            <n-icon :component="AddSharp" />
          </template>
          新增
        </n-button>
      </table-operate>
      <data-table
        :columns="columns"
        :data="list"
        :loading="loading"
      />

      <pagination
        :total="total"
        v-model:page-num="pageNum"
        v-model:page-size="pageSize"
        @update:pageNum="query"
        @update:pageSize="query"
      />
    </div>

    <modal-form
      v-model:show="visible"
      title="字典管理"
      :config="dictFormConfig"
      :width="600"
      :height="400"
      v-model:form="form"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script lang="ts" setup>
  import { h } from 'vue'
  import type { DataTableColumns } from 'naive-ui'
  import type { DictType } from '@/api/power/dict'
  import type { ModalFormConfig } from '@/components/ModalForm/index.vue'

  import { AddSharp } from '@vicons/ionicons5'
  import { NButton, NFlex, NIcon } from 'naive-ui'
  import SearchCirteria from '@/components/SearchCriteria/index.vue'
  import Pagination from '@/components/Pagination/index.vue'
  import TableOperate from '@/components/TableOperate/index.vue'
  import TableButton from '@/components/TableButton/index.vue'
  import ModalForm from '@/components/ModalForm/index.vue'
  import DictTag from '@/components/DictTag/index.vue'

  import {
    saveDictType,
    getDictTypeList,
    deleteDictType,
    getDictType,
    updateDictType
  } from '@/api/power/dict'
  import { useCurd } from '@/hooks/useCrud'
  import { useDict } from '@/hooks/useDict'
  import { useMessage } from 'naive-ui'
  import { useRouter } from 'vue-router'

  import dayjs from 'dayjs'

  const message = useMessage()
  const router = useRouter()

  const { sys_common_status } = useDict('sys_common_status')

  // 窗口显示/隐藏
  const visible = ref(false)

  const form = ref(<DictType>{})

  // 显示新增窗口
  const handleShowModal = async (id: any) => {
    if (typeof id === 'number') {
      const res = await getDictType(id)
      form.value = res.data
    }
    visible.value = true
  }

  // 确认保存
  const handleConfirm = async () => {
    if (form.value.id) {
      const { id, ...arg } = form.value
      await updateDictType(id, arg)
      message.success('修改字典成功')
    } else {
      await saveDictType(form.value)
      message.success('新增字典成功')
    }
    handleCancel()
    query()
  }

  // 取消保存
  const handleCancel = () => {
    form.value = {
      name: '',
      dictType: ''
    }
    visible.value = false
  }

  const { query, list, queryParams, total, pageNum, pageSize, handleDelete, loading } =
    useCurd<DictType>({
      queryFn: getDictTypeList,
      deleteFn: deleteDictType
    })

  const createColumns = (): DataTableColumns<Required<DictType>> => {
    return [
      {
        width: 200,
        align: 'center',
        title: '字典名称',
        key: 'name'
      },
      {
        width: 260,
        align: 'center',
        title: '字典标识',
        key: 'dictType',
        render(row) {
          return h(
            'span',
            {
              class: 'dict-type',
              onClick: () => router.push({ path: 'dict-data/' + row.id })
            },
            { default: () => row.dictType }
          )
        }
      },
      {
        title: '状态',
        key: 'status',
        render: row => h(DictTag, { value: String(row.status), options: sys_common_status.value })
      },
      {
        title: '排序',
        key: 'sort'
      },
      {
        title: '创建时间',
        key: 'createTime',
        align: 'center',
        render: row => dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
      },
      {
        title: '操作',
        key: 'actions',
        align: 'center',
        width: 300,
        render(row) {
          return h(
            NFlex,
            { justify: 'center' },
            {
              default: () => [
                h(
                  TableButton,
                  {
                    type: 'primary',
                    onClick: () => handleShowModal(row.id)
                  },
                  {
                    default: () => '修改'
                  }
                ),
                h(
                  TableButton,
                  {
                    type: 'error',
                    onClick: () => handleDelete(row.id)
                  },
                  {
                    default: () => '删除'
                  }
                )
              ]
            }
          )
        }
      }
    ]
  }

  const columns = createColumns()

  const dictFormConfig = ref<ModalFormConfig[]>([
    {
      type: 'input',
      label: '字典名称',
      key: 'name',
      span: 12,
      show: true
    },
    {
      type: 'input',
      label: '字典标识',
      key: 'dictType',
      span: 12,
      show: true
    },
    {
      type: 'input-number',
      label: '排序',
      key: 'sort',
      span: 12,
      show: true
    },
    {
      type: 'radio',
      label: '状态',
      key: 'status',
      span: 12,
      options: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
      ],
      show: true
    },
    {
      type: 'input',
      label: '备注',
      key: 'remark',
      span: 24,
      show: true
    }
  ])
</script>

<style lang="scss">
  .dict-type {
    cursor: pointer;
    color: var(--n-loading-color);
  }
</style>
